const logResponseBody = function(req, res, next) {
  var oldWrite = res.write,
    oldEnd = res.end

  var chunks = []

  res.write = function(chunk) {
    chunks.push(Buffer.from(chunk))

    oldWrite.apply(res, arguments)
  }

  res.end = function(chunk) {
    if (chunk) chunks.push(Buffer.from(chunk))

    var body = Buffer.concat(chunks).toString('utf8')
    res.locals.body = body

    oldEnd.apply(res, arguments)
  }

  next()
}

module.exports = logResponseBody
